package mall.controller.admin;

import com.google.gson.Gson;
import mall.model.Result;
import mall.model.User;
import mall.service.UserService;
import mall.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
 *
 * @author Yonni
 * @version 1.8.0_201
 * @date 2020-05-29 17:48
 *
 * */
@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        if ("allUser".equals(action)) {
            allUser(request, response);
        } else if ("deleteUser".equals(action)) {
            deleteUser(request, response);
        } else if ("searchUser".equals(action)) {
            searchUser(request, response);
        }
    }

    /**
     * 搜索用户信息
     * 1. 获取get请求参数word
     * 2. 查询数据库，获取满足条件的数据
     * 3. 作出响应
     * */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<User> userList = userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(userList)));
    }

    /**
     * 删除用户信息
     * 1. 获取参数id
     * 2. 根据参数id，删除数据库表user相应数据
     * 3. 作出响应{"code":0}
     * */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        userService.deleteUser(id);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 获取数据库表user中的所有用户信息
     * 1. 查询数据库，获取数据
     * 2. 作出响应{"code":0, "data": [{user1}, {user2}, ...]}
     * */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.allUser();
        response.getWriter().println(gson.toJson(Result.ok(userList)));
    }
}
